<template>
  <div class="mynavbar_container">
    <!--以下是导航栏组件开始-->
    <el-row>
      <el-col :span="16" :offset="4">
        <el-menu
            :default-active="activeIndex"
            class="el-menu-demo"
            mode="horizontal"
            @select="handleSelect"
            background-color="#336699"
            text-color="#fff"
            active-text-color="#ffd04b">
          <div class="mynavbar_logo_div">
            <a href="javascript:void(0);" @click="goHome"><img class="mynavbar_logo_img"
                                                               src="https://img.simoniu.com/vue_logo_200px.png"/>&nbsp;网站名称</a>
          </div>
          <el-menu-item index="/menu1">主选项1</el-menu-item>
          <el-submenu index="">
            <template slot="title">主选项2</template>
            <el-menu-item index="/menu2-1">选项2-1</el-menu-item>
            <el-menu-item index="/menu2-2">选项2-2</el-menu-item>
            <el-menu-item index="/menu2-3">选项2-3</el-menu-item>
          </el-submenu>
          <el-menu-item index="/menu3">主选项3</el-menu-item>
          <el-submenu index="case">
            <template slot="title">案例4</template>
            <el-menu-item index="/case/session">前端session案例</el-menu-item>
            <el-menu-item index="/menu4-2">选项4-2</el-menu-item>
            <el-menu-item index="/menu4-3">选项4-3</el-menu-item>
          </el-submenu>
          <el-menu-item index="/menu5">主选项5</el-menu-item>
          <el-submenu index="users" class="el-submenu-userinfo" v-if="isLogin">
            <template slot="title">
              <el-avatar :size="28"
                         :src="currentLoginUserInfo.avatar"></el-avatar>
              用户名 {{ currentLoginUserInfo.username.substring(0, 6) }}
            </template>
            <el-menu-item index="/users/center"><i class="el-icon-user"></i>个人中心</el-menu-item>
            <el-menu-item index="#"><i class="el-icon-shopping-cart-1"></i>我的订单</el-menu-item>
            <el-menu-item index="#"><i class="el-icon-star-off"></i>我的收藏</el-menu-item>
            <el-menu-item index="#" @click="logout"><i class="el-icon-back"></i>注&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;销
            </el-menu-item>
          </el-submenu>
          <div class="mynavbar_login_div" v-if="!isLogin">
            <router-link to="/login">登录</router-link>
          </div>
        </el-menu>
      </el-col>
    </el-row>
    <!--导航栏组件结束-->
  </div>
</template>

<script>

import {logout, isLogin} from '@/api/users/users'
import store from "@/store";

export default {
  name: "NavBar",
  data() {
    return {
      activeIndex: this.$store.state.currentActiveIndex,
      isLogin: this.$store.state.currentLoginUserStatus,
      currentLoginUserInfo: localStorage.getItem("currentLoginUserInfo") ? JSON.parse(localStorage.getItem("currentLoginUserInfo")) : {
        username: '',
        avatar: 'https://img.simoniu.com/vue-color-avatar11.png'
      }
    }
  },
  async mounted() {
    //解决刷新页面后必须发送请求的bug.
    /*
    window.onbeforeunload = (e)=>{
      console.log("-----------用户点击了刷新页面-------------")
      //e.preventDefault(); //取消刷新；
      isLogin().then(resp=>{
        if(resp.data.code === 200){
          sessionStorage.setItem("currentLoginUserStatus",'true');
          //this.isLogin = true;
          //更新状态管理的状态
          //不推荐直接去修改这个属性
          //this.$store.state.currentLoginUserStatus = true;
          //this.$store.commit('changeCurrentLoginUserStatus',true);
        }else{
          sessionStorage.setItem("currentLoginUserStatus",'false');
          //this.isLogin = false;
          //更新状态管理的状态
          //this.$store.state.currentLoginUserStatus = false;
          //this.$store.commit('changeCurrentLoginUserStatus',false);
        }
      })
    }*/

    //如果localStorage中没有存储用户资料，说明已经注销。
    if (localStorage.getItem("currentLoginUserInfo") === null) {
      this.isLogin = false;
      this.$store.commit('changeCurrentLoginUserStatus', false);
    }

    //刷新页面时如果发现localStorage中已经有用户资料，说明已经登录....
    window.onbeforeunload = (e) => {
      if (localStorage.getItem("currentLoginUserInfo")) {
        this.isLogin = true;
        this.$store.commit('changeCurrentLoginUserStatus', true);
      }
    }

    if (this.isLogin === null) {
      console.log("----------第一次初始化登录状态，发送检查是否已经登录的请求-------------")
      //必须要发送一次检查是否已经登录的请求了。
      await isLogin().then(resp => {
        if (resp.data.code === 200) {
          this.isLogin = true;
          //更新状态管理的状态
          //不推荐直接去修改这个属性
          //this.$store.state.currentLoginUserStatus = true;
          this.$store.commit('changeCurrentLoginUserStatus', true);
        } else {
          this.isLogin = false;
          //更新状态管理的状态
          //this.$store.state.currentLoginUserStatus = false;
          this.$store.commit('changeCurrentLoginUserStatus', false);
        }
      })
    }
    console.log("目前的登录状态是：" + this.isLogin);
    console.log("-------当前登录的用户资料--------");
    console.log(this.currentLoginUserInfo)
  },
  methods: {

    //更新头像的方法
    refreshLoginSuccessUserAvatar(){
      this.currentLoginUserInfo = JSON.parse(localStorage.getItem("currentLoginUserInfo"));
    },

    handleSelect(key, keyPath) {
      console.log(key, keyPath);
      //注意：navbar组件当你点击菜单的时候，它并不会执行路由跳转。
      //怎么办呢？必须手工写路由。
      //注意：传进来的keyPath参数，包含了路由的信息
      this.$router.push({path: keyPath[keyPath.length - 1]}).catch(() => {
      });
      //把你当前选中的菜单的路由保存到vuex状态管理中。
      this.$store.commit('changeCurrentActiveIndex', keyPath[keyPath.length - 1])
    },

    logout() {
      console.log('执行用户注销....');
      logout().then(resp => {
        if (resp.data.code === 200) {
          this.$message({
            type: 'success',
            message: '注销成功！'
          })
          this.$store.commit('changeCurrentLoginUserStatus', false);
          localStorage.removeItem("currentLoginUserInfo");
          this.$store.commit('changeCurrentActiveIndex', '/')

          setTimeout(() => {
            window.location.href = '/login'
          }, 1000);
        }
      })
    },
    goHome() {
      //this.$router.push({path: '/'});
      this.$router.push({path: '/'}).catch(() => {
      });
      this.$store.commit('changeCurrentActiveIndex', '/')
    }
  }
}
</script>

<style scoped>
.mynavbar_container {
  width: 100%;
  margin: 0 auto;
  background-color: #336699;
  /*导航栏固定在页面顶部*/
  top: 0;
  left: 0;
  z-index: 200 !important;; /*这个值不要设置太大，否则会遮盖messagebox*/
  position: fixed;
}

.mynavbar_logo_div {
  float: left;
  width: 120px;
  height: 60px;
  vertical-align: middle;
  color: #ffffff;
}

.mynavbar_logo_div a {
  color: #ffffff;
  text-decoration: none;
  font-size: 12pt;
}

.mynavbar_login_div {
  float: right;
  width: 120px;
  height: 60px;
  line-height: 60px;
  vertical-align: middle;
  color: #ffffff;
  text-align: left;
}

.mynavbar_login_div a {
  color: #ffffff;
  text-decoration: none;
  font-size: 10pt;
}

.mynavbar_logo_img {
  margin: 18px 0px;
  width: 32px;
  height: 32px;
  display: inline;
  vertical-align: middle;
}

.el-menu-item, .el-submenu {
  width: 120px;
  text-align: center;
}

.el-submenu-userinfo {
  width: 200px;
  text-align: center;
}

.el-menu-item a {
  text-decoration: none;
}

.el-menu--horizontal .el-menu .el-menu-item {
  width: 200px;
  text-align: center;
}

</style>